//
//  MusicGenerateViewController.swift
//  NDAi
//
//  Created by 丸子 on 2024/7/25.
//

import UIKit
import SVGAPlayer
class MusicGenerateViewController: BaseViewController {
    var checkId:String?
    var checkTimes: Int = 0
    var isGenerating: Bool = false
    var lastRequestTime: TimeInterval = 0
    let disposeBag = DisposeBag()
    var viewModel:PaintingViewModel?
    private lazy var svgaPlayer: SVGAPlayer = {
        let player = SVGAPlayer()
        player.translatesAutoresizingMaskIntoConstraints = false
        player.loops = 0  // 设置为无限循环
        player.clearsAfterStop = true
        return player
    }()
    private lazy var svgaParser: SVGAParser = {
        return SVGAParser()
    }()
    
    lazy var titleLb: UILabel = {
        let label = UILabel()
        label.text = "歌曲生成中，大约需要3-10分钟请耐心等待"
        label.textColor = Theme.color.text_d1
        label.font = UIFont.pingFangSCRegular(ofSize: 16)
        label.textAlignment = .center
        label.numberOfLines = 0
        return label
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
//        self.navigationController?.navigationBar.isHidden = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
//        self.navigationController?.navigationBar.isHidden = false
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.title = "音乐定制"
        self.view.backgroundColor = UIColor.white
        self.view.addSubviews([svgaPlayer, titleLb])
      
        svgaPlayer.snp.makeConstraints { make in
            make.centerY.equalToSuperview().offset(-80)
            make.centerX.equalToSuperview()
            make.width.height.equalTo(200)
        }
        titleLb.snp.makeConstraints { make in
            make.top.equalTo(svgaPlayer.snp.bottom).offset(16)
            make.centerX.equalToSuperview()
        }
        self.getImageData()
        
        loadLocalSVGA(named: "draw_loading")
        let rightBtn = UIButton(type: .custom)
        rightBtn.setImage(UIImage(named: "icon_music_history"), for: .normal)
        let rightItem = UIBarButtonItem(customView: rightBtn)
        self.navigationItem.rightBarButtonItem = rightItem
        
        rightBtn.setClosureTouchUpInside_k { [weak self] in
            guard let self = self else { return }
            self.navigationController?.pushViewController(MusicHistoryViewController())
        }
        RequestService.instance.getUserInfo()

    }
    private func loadLocalSVGA(named: String) {
        if let filePath = Bundle.main.path(forResource: named, ofType: "svga") {
            svgaParser.parse(with: URL(fileURLWithPath: filePath), completionBlock: { [weak self] videoItem in
                self?.svgaPlayer.videoItem = videoItem
                self?.svgaPlayer.startAnimation()
            }, failureBlock: { error in
                print("加载 SVGA 文件失败: \(error?.localizedDescription ?? "")")
            })
        } else {
            print("未找到名为 \(named) 的 SVGA 文件")
        }
    }
    
    @objc func getImageData(){
        guard let checkId = checkId, checkId.count > 0 else { return }
        let timestamp = Date().timeIntervalSince1970
        if checkTimes > 60 {
            isGenerating = false
            XLog.d("", "绘图超时")
            // stopTimer() // 如果需要停止定时器，请确保实现这个方法
            return
        }
        lastRequestTime = timestamp
        checkTimes += 1
        DispatchQueue.global(qos: .default).async { [weak self] in
            guard let self = self else { return }
            RequestService.instance.getCheckMusic(checkId: checkId) { model in
                if let model = model, let state = model.sts, state == 2 {
                    self.isGenerating = false
                    self.generateSuccess(model: model)//成功了
                }else {
                    self.perform(#selector(self.getImageData), with: nil, afterDelay: 30)
                }
                XLog.d("图像", "完成第\(self.checkTimes)次轮询结果")
            } failureClosure: { error in
                //这里是网络异常
                XLog.d("", error)
            }
        }
    }
   
    func generateSuccess(model:MusicModel){
        let vc = MusicPlayerDetailsViewController()
        vc.model = model
        self.navigationController?.pushViewController(vc)
    }
}
